package com.ossjk.qlh.tgb.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ossjk.qlh.tgb.entity.UserShoppingCart;
import com.ossjk.qlh.tgb.mapper.UserShoppingCartMapper;
import com.ossjk.qlh.tgb.service.IUserShoppingCartService;
import com.ossjk.qlh.tgb.vo.UserShoppingCartDetailVo;
import com.ossjk.qlh.tgb.vo.UserShoppingCartVo;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName UserShoppingCartServiceImpl
 * @Description 用户购物车
 * @Author LZH
 * @Date 2022/1/18 15:53
 */
@Service
public class UserShoppingCartServiceImpl extends ServiceImpl<UserShoppingCartMapper, UserShoppingCart> implements IUserShoppingCartService {

    @Override
    public Page getUserShoppingCartList(Wrapper wrapper, Page page) {

        Page pageVo = this.baseMapper.selectPageVo(page, wrapper);

        List<UserShoppingCartVo> records = pageVo.getRecords();
        for (UserShoppingCartVo userShoppingCartVo : records) {
            String uid = userShoppingCartVo.getUid();
            //根据uid查询用户的购物车
            Integer sum = this.getUserShoppingCarCount(uid);
            userShoppingCartVo.setSum(sum);
        }

        return pageVo;
    }

    @Override
    public Map<String,Object> getShoppingCartByUid(String uid) {
        Map<String,Object> map = new HashMap<>();

        BigDecimal total = new BigDecimal(0);
        List<UserShoppingCartDetailVo> cartList = this.baseMapper.getUserShoppingDetail(uid);
        for (UserShoppingCartDetailVo userShoppingCartDetailVo : cartList) {
            BigDecimal totalPrice = userShoppingCartDetailVo.getPrice().multiply(new BigDecimal(userShoppingCartDetailVo.getCount()));
            userShoppingCartDetailVo.setTotalPrice(totalPrice);
            total = total.add(totalPrice);
        }
        map.put("cartList",cartList);
        map.put("total",total);
        return map;
    }

    /**
     * @method getUserShoppingCarCount
     * 获取用户购物车的总数量
     */
    private Integer getUserShoppingCarCount(String uid) {
        List<Integer> nums = this.baseMapper.getUserShoppingCartCount(uid);
        int sum = 0;
        for (Integer num : nums) {
            sum += num;
        }
        return sum;
    }
}
